package com.zz.info.controller;

import java.io.IOException;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.zz.common.utils.StringUtils;
import com.zz.info.service.LikeService;
import com.zz.info.service.UsercollectionService;
import com.zz.info.utils.FlagUtils;
import com.zz.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zz.common.config.ApplicationContextRegister;
import com.zz.common.utils.MD5Utils;
import com.zz.info.domain.Comment;
import com.zz.info.domain.api.AddCommentRequest;
import com.zz.info.service.InfoService;
import com.zz.info.test.DummyAPIResponse;
import com.zz.system.dao.UserDao;
import com.zz.system.domain.UserDO;
import com.zz.util.InfoResultVOUtil;
import com.zz.util.ResultVOUtil;
import com.zz.vo.InfoResultVO;
import com.zz.vo.ResultVO;

import lombok.extern.slf4j.Slf4j;

/**
 * screen will get data from those API
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class APIController {
    @Resource
    DummyAPIResponse dummyAPIResponse;
    @Autowired
    UserService userService;
    @Autowired
    InfoService infoService;
    @Autowired
    UsercollectionService usercollectionService;
    @Autowired
    LikeService likeService;
    // 顶部类型列表
    @RequestMapping("article/category")
    public InfoResultVO getCategory(){

//        return   InfoResultVOUtil.success(dummyAPIResponse.getCategory());
    	return InfoResultVOUtil.success(infoService.apiGetCategory());
    }
    //根据类型查询文章，这里只返回文章的标题和封面
    @RequestMapping("article/index")
    public InfoResultVO getindex(@RequestParam("category_id") String category_id,@RequestParam("page_index") int page_index,@RequestParam("page_size") int page_size){
        log.info(category_id+"*************category_id");
//        return   InfoResultVOUtil.success(dummyAPIResponse.getindex());
        return InfoResultVOUtil.success(infoService.apiGetIndex(category_id, page_size, page_index));
    }
//根据文章id，返回文章的内容
//    https://life.weisite.org/api/article/detail.html?id=11557
    @RequestMapping("article/detail")
    public InfoResultVO getdetail(@RequestParam("id") String id,@RequestParam(name="page_size", required = false) String page_size){
        log.info(id+"********detail*****id");


        infoService.updateRead(Long.parseLong(id));
//        return   InfoResultVOUtil.success(dummyAPIResponse.getdetail());
        return InfoResultVOUtil.success(infoService.apiGetDetail(id));
    }

    @RequestMapping("article/addComment")
    public InfoResultVO addComment( AddCommentRequest request){
    	Comment comment = new Comment();
    	comment.setContent(request.getContent());
    	comment.setInfoId(Long.parseLong(request.getId()));
    	comment.setOpenId(request.getOpenID());
    	infoService.addComment(comment);

    	return InfoResultVOUtil.success(infoService.getComment(request.getId(), Integer.parseInt(request.getPageSize())));
    }

    @RequestMapping("article/comment")
    public InfoResultVO getComment(@RequestParam("article_id") String id, @RequestParam(name="page_size", required = false) int page_size){
    	return InfoResultVOUtil.success(infoService.getComment(id, page_size));
    }

    @PostMapping("login")
    public ResultVO login(@RequestBody UserDO userDO){
        String password=userDO.getPassword();
        String username=userDO.getUsername();
        password = MD5Utils.encrypt(username, password);
        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);
        UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
        // 查询用户信息
        UserDO user = userMapper.list(map).get(0);

        // 账号不存在
        if (user == null) {
            ResultVOUtil.error(500,"账号或密码不正确");
//            throw new UnknownAccountException("账号或密码不正确");
        }

        // 密码错误
        if (!password.equals(user.getPassword())) {
            ResultVOUtil.error(500,"账号或密码不正确");
//            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        // 账号锁定
        if (user.getStatus() == 0) {
//            throw new LockedAccountException("账号已被锁定,请联系管理员");
            ResultVOUtil.error(500,"账号已被锁定,请联系管理员");
        }

        return   ResultVOUtil.success(user);
    }
    @RequestMapping("byopenId")
    public ResultVO getUserByOpenId(@RequestParam("openId") String openId){
        System.out.println("openId*************"+openId);
        if("".equals(openId)){
            openId="00";
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("openId", openId);
        UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
        // 查询用户信息
        if(userMapper.list(map).isEmpty()){
            return ResultVOUtil.error(500,"账号不存在");
        }else {
            UserDO user = userMapper.list(map).get(0);
            return   ResultVOUtil.success(user);
        }

    }


    @RequestMapping("user/userInfo")
    public InfoResultVO getuserInfoByOpenId(@RequestParam("openId") String openId){
        System.out.println("openId*************"+openId);
        if("".equals(openId)){
            openId="00";
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("openId", openId);
        UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
        // 查询用户信息
        if(userMapper.list(map).isEmpty()){
            return InfoResultVOUtil.error(500,"账号不存在");
        }else {
            UserDO user = userMapper.list(map).get(0);
            return   InfoResultVOUtil.success(user);
        }

    }

    /**
     * 注册用的api
     * @param
     * @return
     */
    @PostMapping("user/register")
    public ResultVO register(UserDO user, HttpServletResponse res) throws IOException {
        List<Long> roles=new ArrayList();
        roles.add(59l);
        user.setRoleIds(roles);
        if(user.getUserId()!=null){
            if (userService.update(user) > 0) {
                return   ResultVOUtil.success(user);
//            res.sendRedirect("http://school.3kkk.xyz/xiaoyuan/?openid="+user.getOpenId()+"&bizid="+user.getDeptId()+"#/");
            }else{
                return   ResultVOUtil.error(500,"error");
            }
        }else{
            user.setPassword("123456");
            user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
            System.out.println(user);
            user.setDeptName("松江大学城" );
            user.setUsername(user.getMobile());
            user.setStatus(1);
            user.setGmtCreate(new Date());
            if (userService.save(user) > 0) {
                return   ResultVOUtil.success(user);
//            res.sendRedirect("http://school.3kkk.xyz/xiaoyuan/?openid="+user.getOpenId()+"&bizid="+user.getDeptId()+"#/");
            }else{
                return   ResultVOUtil.error(500,"error");
            }
        }


    }

    /**
     * 文章点赞
     * @param contentId 文章id info_content.cid
     * @param openId 微信用户唯一openid
     * @return
     */
    @RequestMapping("article/like")
    public InfoResultVO article_like(@RequestParam("article_id") Long contentId,@RequestParam("openId") String openId){
        if(contentId==null){//未验证文章有效
            return InfoResultVOUtil.error(500,"文章不存在");
        }
        UserDO user=null;
        try{
            user=checkUser(openId);
        }catch (Exception e){
            return InfoResultVOUtil.error(500,e.getMessage());
        }
        //点赞 ,取消点赞
        likeService.toggleLike(FlagUtils.LIKETYPE_CONTENT,contentId,user.getUserId()+"");
        return InfoResultVOUtil.success();
    }

    /**
     *
     * @param commentId 评论id
     * @param openId 微信用户唯一openid
     * @return
     */
    @RequestMapping("comment/like")
    public InfoResultVO comment_like(@RequestParam("comment_id") Long commentId,@RequestParam("openId") String openId){
        if(commentId==null){//未验证评论有效
            return InfoResultVOUtil.error(500,"评论不存在");
        }
        UserDO user=null;
        try{
            user=checkUser(openId);
        }catch (Exception e){
            return InfoResultVOUtil.error(500,e.getMessage());
        }
        //点赞 ,取消点赞
        likeService.toggleLike(FlagUtils.LIKETYPE_COMMENT,commentId,user.getUserId()+"");
        return InfoResultVOUtil.success();
    }
    @RequestMapping("article/favorite")
    public InfoResultVO article_collention(@RequestParam("article_id") Long articleId,@RequestParam("openId") String openId){
        if(articleId==null){//未验证文章有效
            return InfoResultVOUtil.error(500,"文章不存在");
        }
        UserDO user=null;
        try{
            user=checkUser(openId);
        }catch (Exception e){
            return InfoResultVOUtil.error(500,e.getMessage());
        }
        //收藏 ,取消收藏
        usercollectionService.toggleCollection(articleId,user.getUserId()+"");
        return InfoResultVOUtil.success();
    }
    //收藏列表 报文
    //{
    //    "code":0,
    //    "data":{
    //        "list":[
    //            {
    //                "id":11493,
    //                "title":"自我剖析——做自己的英雄",
    //                "photo_url":"http://olife.weisite.org/api/common/bdimg.html?url=https%3A%2F%2Fpics3.baidu.com%2Ffeed%2Fadaf2edda3cc7cd904b3cff186f04238b90e9171.jpeg%3Ftoken%3Dd843db2ca524ff6e660f848cbbf39785%26amp%3Bs%3D4F303BC684B22DBF23BC841B0300C0D1",
    //                "read":1498,
    //                "create_time":"2020-10-07",
    //                "source":"燚智社会心理",
    //                "favorite_time":"25分钟前",
    //                "comment_count":2
    //            }
    //        ],
    //        "count":1,
    //        "page":1
    //    },
    //    "msg":"操作成功"
    //}
    @RequestMapping("article/favoriteList")
    public InfoResultVO article_favoriteList(@RequestParam("openId") String openId,@RequestParam("page_index") int page_index,@RequestParam("page_size") int page_size){
        UserDO user=null;
        try{
            user=checkUser(openId);
        }catch (Exception e){
            return InfoResultVOUtil.error(500,e.getMessage());
        }


        return InfoResultVOUtil.success(usercollectionService.apiGetIndex(openId, page_size, page_index));
    }

    private UserDO checkUser(String openId) throws Exception {
        if(StringUtils.isBlank(openId)){
            throw new Exception("账号不存在");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("openId", openId);
        UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
        // 查询用户信息
        List<UserDO> tempUL=userMapper.list(map);
        UserDO user=null;
        if(tempUL.isEmpty()){
            throw new Exception("账号不存在");
        }else if(tempUL.size()!=1){
            throw new Exception("账号异常");
        }else {
            user = tempUL.get(0);
        }
        return user;
    }
}
